const app = getApp(); // 获取全局应用实例
const baseURL = app.globalData.baseURL
const util = require('../../utils/payment.js')
Page({
  data:{
    address: null,
    goodsList: [], // 来自购物车或立即购买
    totalPrice: 0,
    totalPay: 0,
    totalQuantity: 0,  // 总件数
    paymentMethod: 'wechat',

    statusBarHeight: app.globalData.statusBarHeight, // 状态栏高度
    navHeight: app.globalData.navHeight,       // 导航栏总高度
    tabBarHeight: app.globalData.tabBarHeight,  // 底部高度
  },

  // 返回上一页
  navigateBack(delta = 1) { wx.navigateBack() },

  onLoad() {
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on('sendOrderData', (data) => {
       this.loadGoodsData(data)
    })
  },
  // 页面显示时触发
  onShow(){
    this.loadAddress()  // 加载地址
  },
  // 加载商品数据（来自购物车或立即购买）
  loadGoodsData(data) {
    const from = data.goodsType // cart或buyNow
    if(from === 'cart') {
      const cartData = data.selectedItems || []
      this.setData({ goodsList: cartData.filter(item => item.checked) })
    } else {
      const buyNowData = data.selectedItems || []
      this.setData({ goodsList: [buyNowData] })
    }
    this.calculateTotal()
  },

  // 计算总价
  calculateTotal() {
    const { totalAmount, totalCount } = this.data.goodsList.reduce(
      (acc, item) => ({
        totalAmount: acc.totalAmount + (item.price * item.count),
        totalCount: acc.totalCount + item.count
      }),
      { totalAmount: 0, totalCount: 0 } // 初始值
    )
    this.setData({ 
      totalPrice: totalAmount.toFixed(2),
      totalQuantity: totalCount,
      totalPay: totalAmount.toFixed(2) // 如果有优惠后续再扣减
    })
  },

  chooseAddress() {
    wx.navigateTo({
      url: '/pages/address/list/list',
    })
  },

  // 提交订单
  async submitOrder() {
    if (!this.data.address) {
      return wx.showToast({ title: '请选择收货地址', icon: 'none' })
    }
    try {
      const orderData = {
        address: this.data.address,
        goods: this.data.goodsList,
        total: this.data.totalPay,
        payment: this.data.paymentMethod,
        mobile: wx.getStorageSync('mobile')
      }
      // util.startPayment(orderData) // 调用utils的开始支付
        wx.request({
          url: baseURL + 'api/paymentV3/', // 微信支付V3版本
          method: 'POST',
          dataType: 'json',
          responseType: 'text',
          header: { 'Authorization': 'Bearer ' + wx.getStorageSync('token').access },
          data: { orderData: orderData },
          success: (res) => {
            const order = res.data   // 后端传来的统一下单数据
            // const orderId = order.out_trade_no  // 后端生成的订单号
            // 调起微信支付
            wx.requestPayment({
              timeStamp: order.timeStamp, //'后端生成的时间戳'
              nonceStr: order.nonce_str, //'后端生成的随机字符串'
              package: `prepay_id=${order.prepay_id}`, // 正确拼接
              signType: 'RSA',
              paySign: order.pay_sign, //'后端生成的签名'
              success: (res) => {
                wx.showToast({title: '支付成功'})
                //跳转到我的订单
                wx.switchTab({ url: '/pages/my/my', })
              },
              fail: (err) => {
                wx.showToast({title: '支付失败!'})
              },
              'complete': () => {
                //刷新页面
                // window.location.reload();
              }
            })
          }
        })
    } catch (error) {
      wx.showToast({ title: '订单提交失败', icon: 'none' })
    }
  },

  // 地址加载方法
  loadAddress() {
    // 先尝试读取本地缓存
    try {
      const defaultAddress = this.getDefaultAddress();  // 获取默认地址
      if (defaultAddress && this.validateAddress(defaultAddress)) {
        this.setData({ address: defaultAddress })
        return
      }else{
          this.getWechatAddress()  // 缓存不存在则尝试获取微信地址
      }
    } catch (error) {
      console.error('地址读取失败:', error)
    }
  },

  // 验证地址完整性
  validateAddress(address) {
    const requiredFields = [
      'userName', 'telNumber', 
      'province', 'city', 'county', 'detail', 
      // 'provinceName', 'cityName', 'countyName', 'detailInfo'
    ]
    return requiredFields.every(field => !!address[field])
  },

  // 获取微信地址（需用户授权）
  getWechatAddress() {
    // 检查权限状态
    wx.getSetting({
      withSubscriptions: true,
      success: (res) => {
        if (res.authSetting['scope.address']) {
          this.chooseWechatAddress()
        } else {
          this.showAuthGuide()
        }
      }
    })
  },

  // 主动调起地址选择
  chooseWechatAddress() {
    wx.chooseAddress({
      success: (res) => {
        //重新解构成合规的键名
        const { userName, telNumber, 
                provinceName:province, 
                cityName: city, 
                countyName: county, 
                detailInfo: detail } = res;
        const convertedRes  = { userName, telNumber, province, city, county, detail };
        if (this.validateAddress(convertedRes )) {
          this.saveAddress(convertedRes)
        } else {
          wx.showToast({ title: '地址信息不完整', icon: 'none' })
        }
      },
      fail: (err) => {
        console.error('地址选择中断:', err)
        if (err.errMsg.includes('auth deny')) {
          this.showAuthGuide()
        }
      }
    })
  },

  // 保存地址到缓存和页面
  saveAddress(address) {
    try {
      wx.setStorageSync('address', address)
      const newAddress = this.formatWechatAddress(address)
      wx.setStorageSync('addressList', [newAddress])
      this.setData({ address: newAddress })
    } catch (error) {
      wx.showToast({ title: '地址保存失败', icon: 'none' })
    }
  },

    // 格式化微信地址
    formatWechatAddress(res) {
      return {
        id: Date.now().toString(),
        userName: res.userName,
        telNumber: res.telNumber,
        province: res.province,
        city: res.city,
        county: res.county,
        detail: res.detail,
        isDefault: true
      }
    },

  // 显示授权引导
  showAuthGuide() {
    wx.showModal({
      title: '需要地址权限',
      content: '请允许我们获取您的收货地址',
      confirmText: '去设置',
      success: (res) => {
        if (res.confirm) {
          wx.openSetting({
            success: (res) => {
              if (res.authSetting['scope.address']) {
                this.chooseWechatAddress()
              }
            }
          })
        }
      }
    })
  },

  // 安全获取默认地址
  getDefaultAddress() {
    try {
      // 1. 类型安全校验
      const localAddress = wx.getStorageSync('addressList') || [];
      // 2. 强化数据校验
      if (!Array.isArray(localAddress)) {
        console.error('addressList 不是数组格式，已重置');
        wx.setStorageSync('addressList', []);
        return null;
      }
      // 3. 精准查找逻辑（支持多种数据格式）
      const defaultItem = localAddress.find(item => {
        // 3.1 处理字段可能不存在的情况
        if (!Object.prototype.hasOwnProperty.call(item, 'isDefault')) {
          return false;
        }
        // 3.2 兼容不同数据类型（字符串/数字/布尔）
        const isDefault = Boolean(item.isDefault);
        // 3.3 返回严格匹配项
        return isDefault === true;
      });
      // 4. 检查是否找到有效项
      if (defaultItem) {
        return defaultItem;
      }
      // 5. 降级处理：找最后修改的地址
      // const sortedByTime = [...localAddress].sort((a, b) => 
      //   (b.updateTime || 0) - (a.updateTime || 0)
      // );
      // return sortedByTime[0] || null;
    } catch (error) {
      console.error('获取地址失败:', error);
      return null;
    }
  },


})
